
const { endpoints, jsonHeaders, ENV } = require('../../utils/api');

Page({
  data: {
    imgBaseUrl: '',
    query: '',
    activeCat: '全部',
    categories: ['全部', '校园', '建设', '活动'],
    allPhotos: [],
    photos: [],
    pageIndex: 1,
    pageSize: 12,
    hasMore: true,
    loading: false,
    refreshing: false,
    showTop: false
  },

  onLoad() {
    this.setData({ imgBaseUrl: ENV.imgBaseUrl || '' });
    this.fetchPhotos(true);
  },

  // 从后端接口获取图片数据
  fetchPhotos(reset = false) {
    if (this.data.loading) return;
    this.setData({ loading: true });

    // 从后端接口获取数据
    wx.request({
      url: endpoints.PHOTO_LIST,
      method: 'GET',
      header: jsonHeaders(),
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          // 处理接口返回的数据格式，转换成前端需要的格式
          const list = res.data.data.map((item, index) => ({
            id: index + 1,
            url: item.imgUrl,
            caption: item.desc,
            cat: item.type
          }));

          if (reset) {
            this.setData({ allPhotos: list, pageIndex: 1, photos: [], hasMore: true });
          } else {
            this.setData({ allPhotos: list });
          }
          this.applyFilters(true);
        } else {
          console.error('获取图片列表失败:', res);
          // 如果接口调用失败，仍然使用原来的静态数据作为备选方案
          this.useStaticData(reset);
        }
      },
      fail: (err) => {
        console.error('请求图片列表接口失败:', err);
        // 如果网络请求失败，使用静态数据作为备选方案
        this.useStaticData(reset);
      },
      complete: () => {
        this.setData({ loading: false, refreshing: false });
      }
    });
  },

  // 备选方案：使用静态数据
  useStaticData(reset = false) {
    const list = [
      { id: 1, url: 'oldPic-agriculture.png', caption: '劳动与农业实践', cat: '活动' },
      { id: 2, url: 'oldPic-building1.png', caption: '早期教学楼', cat: '建设' },
      { id: 3, url: 'oldPic-building2.png', caption: '图书馆旧影', cat: '建设' },
      { id: 4, url: 'oldPic-building3.png', caption: '实验楼奠基', cat: '建设' },
      { id: 5, url: 'oldPic-guide.png', caption: '新生入学引导', cat: '校园' },
      { id: 6, url: 'oldPic-industy.png', caption: '产学研合作', cat: '活动' },
      { id: 7, url: 'oldPic-lab.png', caption: '早期实验室', cat: '校园' },
      { id: 8, url: 'oldPic-military.png', caption: '军训剪影', cat: '活动' },
      { id: 9, url: 'oldPic-planToBuild.png', caption: '校园总体规划', cat: '建设' },
      { id: 10, url: 'oldPic-view.png', caption: '校园风貌', cat: '校园' },
      { id: 11, url: 'oldPic-viewGroupPhoto.png', caption: '毕业留影', cat: '校园' },
      { id: 12, url: 'oldPic-agriculture.png', caption: '劳动教育', cat: '活动' },
      { id: 13, url: 'oldPic-building1.png', caption: '教学楼翻新', cat: '建设' },
      { id: 14, url: 'oldPic-building2.png', caption: '藏书楼记忆', cat: '建设' },
      { id: 15, url: 'oldPic-building3.png', caption: '新校区建设', cat: '建设' }
    ];

    if (reset) {
      this.setData({ allPhotos: list, pageIndex: 1, photos: [], hasMore: true });
    } else {
      this.setData({ allPhotos: list });
    }
    this.applyFilters(true);
  },

  applyFilters(resetPage = false) {
    const q = (this.data.query || '').trim().toLowerCase();
    const cat = this.data.activeCat;
    let arr = [...this.data.allPhotos];
    if (cat && cat !== '全部') arr = arr.filter(it => it.cat === cat);
    if (q) arr = arr.filter(it => (it.caption||'').toLowerCase().includes(q));

    let pageIndex = this.data.pageIndex;
    if (resetPage) pageIndex = 1;

    const start = (pageIndex - 1) * this.data.pageSize;
    const next = arr.slice(start, start + this.data.pageSize);
    const hasMore = start + this.data.pageSize < arr.length;

    this.setData({
      photos: pageIndex === 1 ? next : this.data.photos.concat(next),
      hasMore,
      pageIndex
    });
  },

  onInput(e) { this.setData({ query: e.detail.value || '' }); },
  onSearch() {
    this.setData({ pageIndex: 1, photos: [], hasMore: true });
    this.applyFilters(true);
  },
  switchCat(e) {
    const cat = e.currentTarget.dataset.cat;
    this.setData({ activeCat: cat, pageIndex: 1, photos: [], hasMore: true });
    this.applyFilters(true);
  },

  onRefresh() { this.setData({ refreshing: true }); this.fetchPhotos(true); },
  onReachBottom() { if (!this.data.hasMore || this.data.loading) return; this.setData({ pageIndex: this.data.pageIndex + 1 }); this.applyFilters(false); },

  preview(e) {
    const index = e.currentTarget.dataset.index;
    const urls = this.data.photos.map(p => p.url.startsWith('http') ? p.url : (this.data.imgBaseUrl + p.url));
    wx.previewImage({ current: urls[index], urls });
  },

  backToTop() { wx.pageScrollTo({ scrollTop: 0, duration: 300 }); },

  onPageScroll(e) { this.setData({ showTop: e.scrollTop > 600 }); }
});